/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * @author 品讯科技
 */

package com.px.pa.modulars.circle.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.px.basic.alone.core.base.BaseApiController;
import com.pig4cloud.pig.common.core.util.R;
import com.px.basic.alone.security.annotation.Inner;
import com.px.pa.constants.CollectionStatusEnum;
import com.px.pa.constants.IsPraiseEnum;
import com.px.pa.modulars.circle.entity.*;
import com.px.pa.modulars.circle.service.*;
import com.px.pa.modulars.utils.TenantController;
import com.px.pa.modulars.utils.TextCensor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


/**
 * 
 *
 * @author 品讯科技
 * @date 2024-08
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/circledynamiccommentcomment" )
@Api(value = "circledynamiccommentcomment", tags = "管理")
public class CircleDynamicCommentCommentController extends TenantController {

    private final  CircleDynamicCommentCommentService circleDynamicCommentCommentService;
    private final CircleDynamicCommentService circleDynamicCommentService;
    private final CircleUserService circleUserService;
    private final CircleDynamicService circleDynamicService;
    private final CircleOrganizationalService circleOrganizationalService;
    private final CircleDynamicCollectionService circleDynamicCollectionService;
    private final CircleDynamicCommentPraiseService circleDynamicCommentPraiseService;
    private final CircleNoticeConfigService circleNoticeConfigService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page/list" )
    @Inner(value = false)
    public R getCircleDynamicCommentCommentPage(@RequestParam("page") Integer page,
                                                @RequestParam("pageSize") Integer pageSize,
                                                @RequestParam("circleDynamicCommentId") Integer circleDynamicCommentId) {
        Map<String,Object> map = new HashMap<>();
        Integer userId = super.getCurrentId();
        if(userId == null){
            return R.failed().setMsg("请登录").setCode(401);
        }
        CircleDynamicComment circleDynamicComment = circleDynamicCommentService.getById(circleDynamicCommentId);
        //点赞数
        int praiseNum =  circleDynamicCommentPraiseService.count(new QueryWrapper<CircleDynamicCommentPraise>().eq("circle_dynamic_comment_id",circleDynamicComment.getId()));
        circleDynamicComment.setPraiseNum(praiseNum);
        //评论数
        int commentNum = circleDynamicCommentCommentService.count(new QueryWrapper<CircleDynamicCommentComment>().eq("circle_dynamic_comment_id",circleDynamicComment.getId()));
        circleDynamicComment.setCommentNum(commentNum);
        int count =  circleDynamicCommentPraiseService.count(new QueryWrapper<CircleDynamicCommentPraise>()
                .eq("circle_dynamic_comment_id",circleDynamicComment.getId())
        .eq("uid",userId));
        if(count ==0){
            circleDynamicComment.setIsPraise(IsPraiseEnum.IS_PRAISE_ENUM_TWO.getValue());
        }else {
            circleDynamicComment.setIsPraise(IsPraiseEnum.IS_PRAISE_ENUM_ONE.getValue());
        }
        map.put("circleDynamicComment",circleDynamicComment);
        CircleUser circleUser = circleUserService.getById(circleDynamicComment.getUid());
        CircleOrganizational circleOrganizational = circleOrganizationalService.getById(circleUser.getOrganizationalId());
        circleUser.setOrganizationalName(circleOrganizational.getName());
        circleDynamicComment.setCircleUser(circleUser);
        CircleDynamic circleDynamic = circleDynamicService.getById(circleDynamicComment.getDynamic());
        //是否被收藏
        int collectionNum =  circleDynamicCollectionService.count(new QueryWrapper<CircleDynamicCollection>().eq("uid",userId).eq("dynamic",circleDynamic.getId()));
        if(collectionNum == 0){
            circleDynamic.setCollectionStatus(CollectionStatusEnum.COLLECTION_STATUS_ENUM_TWO.getValue());
        }else {
            circleDynamic.setCollectionStatus(CollectionStatusEnum.COLLECTION_STATUS_ENUM_ONE.getValue());
        }
       int comment = circleDynamicCommentService.count(new QueryWrapper<CircleDynamicComment>().eq("dynamic",circleDynamic.getId()));
        circleDynamic.setCommentNum(comment);
        map.put("circleDynamic",circleDynamic);

        Page<CircleDynamicCommentComment> circleDynamicCommentCommentPage =  circleDynamicCommentCommentService.page(new Page(page,pageSize),new QueryWrapper<CircleDynamicCommentComment>()
                .eq("circle_dynamic_comment_id",circleDynamicCommentId)
                .orderByDesc("creat_time"));

        circleDynamicCommentCommentPage.getRecords().forEach(a->{
            a.setCreateTime(a.getCreatTime());
          CircleUser circleUser1 = circleUserService.getById(a.getUid());
         CircleOrganizational circleOrganizational1 = circleOrganizationalService.getById(circleUser1.getOrganizationalId());
            circleUser1.setOrganizationalName(circleOrganizational1.getName());
            a.setCircleUser(circleUser1);
        });

        //添加浏览量
        CircleDynamicComment circleDynamicComment1 =  circleDynamicCommentService.getById(circleDynamicCommentId);
        if(circleDynamicComment1.getViews() == null){
            circleDynamicComment1.setViews(1);
        }else {
            circleDynamicComment1.setViews(circleDynamicComment1.getViews() + 1);
        }
        circleDynamicCommentService.updateById(circleDynamicComment1);
        map.put("circleDynamicCommentCommentPage",circleDynamicCommentCommentPage);
        return R.ok(map);
    }

    /**
     * 问答新增
     * @param circleDynamicCommentComment 
     * @return R
     */
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping("/addNew")
    @Inner(value = false)
    public R save(@RequestBody CircleDynamicCommentComment circleDynamicCommentComment) {
        Integer userId = super.getCurrentId();
        if(userId == null){
            return R.failed().setMsg("请登录").setCode(401);
        }
        if(StringUtils.isNotEmpty(circleDynamicCommentComment.getContent())){
            TextCensor textCensor  = new TextCensor();
            Boolean b = textCensor.baidu(circleDynamicCommentComment.getContent(),redisHelper);
            if(!b){
                return R.failed("400","存在官方默认违禁词库不合规");
                //return R.ok("400","存在官方默认违禁词库不合规");
            }
        }
        String tenant = super.getTenant();
        circleDynamicCommentComment.setUid(userId);
        circleDynamicCommentComment.setTenantCode(tenant);
        circleDynamicCommentComment.setCreatTime(LocalDateTime.now());
        return R.ok(circleDynamicCommentCommentService.save(circleDynamicCommentComment));
    }


    /**
     * 文章评论的评论新增
     * @param circleDynamicCommentComment
     * @return R
     */
    @ApiOperation(value = "文章评论的评论新增", notes = "文章评论的评论新增")
    @PostMapping("/dynamic/addNew")
    @Inner(value = false)
    public R saveDynamic(@RequestBody CircleDynamicCommentComment circleDynamicCommentComment) {
        Integer userId = super.getCurrentId();
        if(userId == null){
            return R.failed().setMsg("请登录").setCode(401);
        }
        if(StringUtils.isNotEmpty(circleDynamicCommentComment.getContent())){
            TextCensor textCensor  = new TextCensor();
            Boolean b = textCensor.baidu(circleDynamicCommentComment.getContent(),redisHelper);
            if(!b){
                return R.failed("400","存在官方默认违禁词库不合规");
            }
        }
        String tenant = super.getTenant();
        circleDynamicCommentComment.setUid(userId);
        circleDynamicCommentComment.setTenantCode(tenant);
        circleDynamicCommentComment.setCreatTime(LocalDateTime.now());
        //发送评论通知
        ThreadUtil.execute(() -> {
         CircleUser circleUser =   circleUserService.getById(userId);
            circleNoticeConfigService.problemAnswer1(circleUser.getName(),circleDynamicCommentComment.getDynamic(),circleDynamicCommentComment.getContentUser(),tenant);
        });
        return R.ok(circleDynamicCommentCommentService.save(circleDynamicCommentComment));
    }



}
